/*
 *  Copyright 2008 The MITRE Corporation (http://www.mitre.org/). All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package org.mitre.lattice.eav;

import java.net.URLEncoder;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.mitre.mrald.util.Config;
import org.mitre.mrald.util.MraldException;
/**
 *@author     Gail Hamilton
 *@created
 *@version    1.0
 *@see        java.lang.Object
 */
public class ValueElement extends EavElement
{
	/**
	 *  Description of the Field
	 */

	String filterColumn;
	String filterValue;


	/**
	 *  Constructor for the QueryElements object
	 *
	 *@since
	 */
	public ValueElement()  throws MraldException
	{
		super(new String("Value"));
	}


	/**
	 */
	protected void init()  throws MraldException
	{
		//Set up the query that will be used to return the results

		setColName("subject_id");
		if (getDisplayColumn().equals(""))
		{
			setInitQuery("SELECT subject_id, entity.name, attribute.name, value, date from Subject_values, attribute, entity where entity.entity_id = attribute.entity_id AND Subject_values.attribute_id = attribute.attribute_id  ");

			whereAnd = " AND ";
		} else
		{
			setColCount(3);
			setInitQuery(" SELECT entity.name, attribute.name, value, " + getColName() + " from Subject_values, attribute, entity where entity.entity_id = attribute.entity_id AND Subject_values.attribute_id = attribute.attribute_id  ");
			whereAnd = " AND ";
		}

	}


	/**
	 *@param  value  The new colValue value
	 */
	public void setColValue(String value)
	{
		//MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "ValueElement : setColValue  value " + value);

		String[] values = value.split("~");

		super.setColValue(values[0]);

		if (values.length > 2)
		{
			filterColumn = values[1];
			filterValue = values[2];

		}
	}


	/**
	 *@param  columnNo            Description of the Parameter
	 *@return                     The HTML for inclusion in the second form
	 *      building page.
	 *@exception  MraldException  Description of the Exception
	 */
	protected StringBuffer outputRow(int columnNo) throws MraldException
	{
		try
		{
			if (!isTable)
				return outputRowNonTable(columnNo);

			StringBuffer ret = new StringBuffer();

			ret.append("<tr>");
			for (int i = 1; i < columnNo + 1; i++)
			{
				if (getPrintVert())
				{
					ret.append("<tr>");
				}

				if (columnNo == 1)
				{
					ret.append("<td><a href='eavFrame.jsp?classType=" + getType() + "&colName=" + URLEncoder.encode(getColName() ,"UTF-8")+ "&colValue=" + URLEncoder.encode(getRs().getString(getColName()),"UTF-8") + "' target=\"_parent\">" + getRs().getString(i) + "</a></td>");

				} else
				{
					ret.append("<td>" + getRs().getString(i) + "</td>");
				}
				if (getPrintVert())
				{
					ret.append("</tr>");
				}
			}
			ret.append("</tr>");
			setColValue(getRs().getString(getColName()));
			return ret;
		} catch (SQLException s)
		{
			throw new MraldException(s);
		}
		catch (java.io.UnsupportedEncodingException s)
		{
			throw new MraldException(s);
		}
	}

	/**
	 *@param  columnNo            Description of the Parameter
	 *@return                     The HTML for inclusion in the second form
	 *      building page.
	 *@exception  MraldException  Description of the Exception
	 */
	protected StringBuffer outputRowNonTable(int columnNo) throws MraldException
	{
		try
		{
			StringBuffer ret = new StringBuffer();

			for (int i = 1; i < columnNo + 1; i++)
			{
				/*if (getPrintVert())
				{
					ret.append("<p class=\"sideBarTitle\">");
				}*/

				if (columnNo == 1)
				{

					ret.append("<p class=\"sideBarTitle\">");
					ret.append(getRs().getString(i) );
					hasDiv = true;
					String temp = "<a onClick=\"toggle('<:IDName:>', 'images/')\" ><img id=\"<:IDName:>Image\" src=\"images/plus.gif\"></a><div id=\"<:IDName:>\" style=\"display:block;\" class=\"leftSideBar\">";
					temp = temp.replaceAll("<:IDName:>",  getRs().getString(i));
					// ret.append("<a onClick=\"toggle('<:IDName:>', 'images/')\" ><img id=\"<:IDName:>Image\" src=\"images/plus.gif\"></a><div id=<:IDName:> style=\"display:block;\" class=\"leftSideBar\">");
					ret.append(temp);
					endSection="</div></p>";

				}
				else
				{
					ret.append( getRs().getString(i)) ;
				}
				if (getPrintVert())
				{
						//ret.append("</p>");
						ret.append("<br/>");
				}

			}
			if (hasDiv)
			{

				   //ret.append("<a onClick=\"toggleNonId(this)\" ><img src=\"images/plus.gif\"></a><div style=\"display:block;\" class=\"leftSideBar\">");

			}
			else
			{
				//ret.append("</p>");
			}
			setColValue(getRs().getString(getColName()));
			return ret;

		} catch (SQLException s)
		{
			throw new MraldException(s);
		}
	}

	/**
	 *@return                     The HTML for inclusion in the second form
	 *      building page.
	 *@exception  MraldException  Description of the Exception
	 */
	public String insertHtml() throws MraldException
	{
		try
		{
			/*
			 *  prebuild the drop down lists
			 *  they'll be modified later for the specific drop downs
			 */
			setColCount(2);

			String query = " select entity_id, name from entity order by name ";

			ResultSet rs = runQuery(query);

			String entityDropDown = null;
			String selected = "";

			int tmpcount=0;
			while (rs.next())
			{
				tmpcount++;
				//if (tmpcount > 15) break;
				if (rs.getString("entity_id").equals(filterValue))
				{
					selected = "selected";
				}

				entityDropDown = entityDropDown + "<option value=\"" +URLEncoder.encode(rs.getString("entity_id"),"UTF-8")+ "\" " + selected + ">" + rs.getString("name") + "</option>";
				selected = "";
			}

			query = " select attribute_id, name from attribute ";
			StringBuffer attrVal = new StringBuffer();
			String[] columns = new String[]{"attribute_id", "value"};
			String[] columnNames = new String[]{"Attribute", "Value"};
			String tableName = "subject_values";

			if (filterColumn != null)
			{
				query = query + " where " + filterColumn + " = " + filterValue;

				rs = runQuery(query);

				int count = 0;
				int colStart = 4;
				while (rs.next())
				{
					count++;
					attrVal.append("<tr>");
					//dropDown = dropDown + "<option value=\""+  rs.getString("attribute_id")  + "\">" + rs.getString("name") + "</option>";
					for (int i = 0; i < columns.length; i++)
					{
						String insertCount = (colStart + count) + "" + i;
						if (i == 0)
						{
							attrVal.append("<td><b>" + rs.getString("name") + "</b>");
							attrVal.append("<input type=\"hidden\" value=\"Table:" + tableName + "~Field:" + columns[i] + "~Order:" + (colStart + i) + "~Type:String~Value:" + rs.getString(columns[i]) + "~SqlThread:" + count + "\" name=\"Insert" + insertCount + "\"/><br/></td>");
						} else
						{
							attrVal.append("<td><input type=\"text\" name=\"Insert" + insertCount + "\"></input>");
							attrVal.append("<input type=\"hidden\" value=\"Table:" + tableName + "~Field:" + columns[i] + "~Order:" + (i + 1) + "~Type:String~SqlThread:" +  count + "\" name=\"Insert" + insertCount + "\"/><br/></td>");
						}
					}
					attrVal.append("</tr>");
				}
				rs.close();
			}
			StringBuffer ret = new StringBuffer();

			columns = new String[]{"subject_id", "entity_id", "date"};
			columnNames = new String[]{"Subject Id", "Select Test", "Date"};

			for (int i = 0; i < columns.length; i++)
			{
				String value = "";
				if (getColName().equals(columns[i]))
				{
					value = getColValue();
				}
				String input = "<tr><td><b>" + columnNames[i] + "</b></td><td><input type=\"text\" length=\"30\" name=\"Insert" + i +
					"\" value=\"" + value + "\"/><input type=\"hidden\" value=\"Table:!All~SqlThread:-1~Field:" + columns[i] + "~Order:" + i + "~Type:String\" name=\"Insert" + i + "\"/><br/></td></tr>";

				if (columns[i].equals("entity_id"))
				{
					String params = "'show=Subject&classType=Subject&colName=" + getColName() + "&colValue=" + URLEncoder.encode(getColValue(),"UTF-8") + "'";

					input = "<tr><td><b>" + columnNames[i] + "</b></td><td><select name=\"Entity\"  onChange=\"filter(this.value,  " + params + ")\"><option></option>" + entityDropDown + "</select>" +
						"<br/></td></tr>";
				}
				else if (columns[i].equals("date"))
				{
					String calendar = "<SCRIPT LANGUAGE=\"JavaScript\">var cal1 = new CalendarPopup();</SCRIPT><a HREF=\"#\" onClick=\"cal1.select(document.o.Insert"+ i +"[0],'anchor1','MM/dd/yyyy'); return false;\" TITLE=\"cal1.select(document.o.Insert" + i + "[0],'anchor1','MM/dd/yyyy'); return false; \"  NAME=\"anchor1\" ID=\"anchor1\" ><img src=\"" + Config.getProperty("BaseUrl") +"/cal.gif\" width=\"17\" height=\"17\" border=\"0\" alt=\"Click Here to Pick up the timestamp\"></a>";

					input = "<tr><td><b>" + columnNames[i] + "</b></td><td><input type=\"text\" length=\"30\" name=\"Insert" + i +
					"\" value=\"" + value + "\"/><input type=\"hidden\" value=\"Table:!All~SqlThread:-1~Field:" + columns[i] + "~Order:" + i + "~Type:String\" name=\"Insert" + i + "\"/>" + calendar + "<br/></td></tr>";

				}
				ret.append(input);
			}
			ret.append("<tr><td></td><td></td></tr>");

			this.close();
			return ret.toString() + attrVal.toString();
		} catch (SQLException e)
		{
			throw new MraldException();
		}
		catch (java.io.UnsupportedEncodingException e)
		{
			throw new MraldException();
		}
	}


	/**
	 *@return    The HTML for inclusion in the second form building page.
	 */
	public String deleteHtml()
	{
		/*
		 *  prebuild the drop down lists
		 *  they'll be modified later for the specific drop downs
		 */
		StringBuffer ret = new StringBuffer();

		return ret.toString();
	}


	/**
	 *@return    The HTML for inclusion in the second form building page.
	 */
	public String updateHtml()
	{
		/*
		 *  prebuild the drop down lists
		 *  they'll be modified later for the specific drop downs
		 */
		StringBuffer ret = new StringBuffer();

		return ret.toString();
	}

}

